<!-- 知识管理 -->
<template>
  <div>
    <CommonSearch @search="query" @reset="reset">
      <el-col :span="8">
        <el-form-item label="标题">
          <el-input
            v-model="queryParams.condition.title"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="所属专家">
          <SearchSelect
            clearable
            v-model="queryParams.condition.expertId"
            placeholder="请选择"
            :url="pageKnowledgeExpert"
            :payload="{}"
            :valueFormat="
              (item) => {
                return item.id;
              }
            "
            :labelFormat="
              (item) => {
                return item.name;
              }
            "
          ></SearchSelect>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="所属品类" prop="produceCategoryId">
          <QueryCategoryTree
            v-model="queryParams.condition.produceCategoryId"
            :url="queryProduceCategoryTree"
            :payload="{}"
            :cascaderProps="{
              children: 'subProduceCategoryList',
              label: 'name',
              value: 'id',
            }"
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="所属分类" prop="serviceCatgoryCode">
          <QueryCategoryTree
            v-model="queryParams.condition.serviceCatgoryCode"
            cacheValue="SERVICE_CATGORY"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="是否推荐">
          <DictSelect
            v-model="queryParams.condition.recommend"
            :defaultOptions="options.recommend"
            placeholder="请选择状态"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="发布状态">
          <DictSelect
            v-model="queryParams.condition.publishStatus"
            :defaultOptions="options.publishStatus"
            placeholder="请选择状态"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </CommonSearch>

    <el-row class="cardMiniBar">
      <el-col :span="24">
        <div class="fr">
          <el-button type="primary" @click="add" size="small">新增</el-button>
          <el-button @click="batchPublish" size="small">批量发布</el-button>
          <el-button @click="revokeBatchPublish" size="small"
            >批量撤销发布</el-button
          >
          <el-button @click="batchRecommended" size="small">批量推荐</el-button>
          <el-button @click="revokeBatchRecommended" size="small"
            >批量取消推荐</el-button
          >
        </div>
      </el-col>
    </el-row>

    <div class="cardBody">
      <edu-table
        ref="mainTable"
        :data="tableList"
        :pageSize="queryParams.pageSize"
        :pageNum="queryParams.pageNum"
        :total="queryParams.total"
        @page-change="handleCurrentChange"
        :order="true"
        :selection="true"
      >
        <el-table-column label="标题" prop="title" />
        <el-table-column label="专家名称" prop="expertName" />
        <el-table-column label="专家领域" prop="fieldName" />
        <el-table-column label="发布时间" prop="publishTime" width="160" />
        <el-table-column label="发布状态" prop="publishStatus">
          <template slot-scope="scope">
            {{ renderOption(scope.row.publishStatus, "publishStatus") }}
          </template>
        </el-table-column>
        <el-table-column label="是否推荐" prop="recommend">
          <template slot-scope="scope">
            {{ renderOption(scope.row.recommend, "recommend") }}
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="180px">
          <template slot-scope="scope">
            <el-button
              type="text"
              v-if="scope.row.publishStatus == 2"
              @click="edit(scope.row)"
              size="small"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              v-if="scope.row.publishStatus == 2"
              @click="handlerDelete(scope.row)"
              size="small"
            >
              删除
            </el-button>

            <el-button
              type="text"
              v-if="scope.row.publishStatus == 2"
              @click="publish(scope.row)"
              size="small"
              >发布</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.publishStatus == 1"
              @click="revokePublish(scope.row)"
              size="small"
              >取消发布</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.recommend == 2"
              @click="recommended(scope.row)"
              size="small"
              >推荐</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.recommend == 1"
              @click="revokeRecommended(scope.row)"
              size="small"
              >取消推荐</el-button
            >
          </template>
        </el-table-column>
      </edu-table>
    </div>

    <edu-dialog
      :title.sync="dialogConfig.title"
      :visible.sync="dialogConfig.showDialog"
      @close="handleDialogClose"
      width="70%"
      height="600px"
    >
      <el-form
        ref="dialogForm"
        :model="dialogConfig.formData"
        :rules="dialogConfig.action === 'view' ? {} : dialogConfig.rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="dialogConfig.formData.title" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="摘要" prop="resume">
              <el-input
                v-model="dialogConfig.formData.resume"
                :show-word-limit="true"
                :maxlength="200"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专家" prop="expertId">
              <SelectProfession
                ref="selectProfession"
                v-model="dialogConfig.formData.expertId"
                v-bind:valueText="dialogConfig.formData.expertName"
                :nameReadonly="true"
              ></SelectProfession>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专家领域" prop="fieldCode">
              <QueryCategoryTree
                v-model="dialogConfig.formData.fieldCode"
                :payload="{ dictType: 'EXPERT_FIELD' }"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所属品类" prop="produceCategoryId">
              <QueryCategoryTree
                v-model="dialogConfig.formData.produceCategoryId"
                :url="queryProduceCategoryTree"
                :payload="{}"
                :cascaderProps="{
                  children: 'subProduceCategoryList',
                  label: 'name',
                  value: 'id',
                }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属分类" prop="serviceCatgoryCode">
              <QueryCategoryTree
                v-model="dialogConfig.formData.serviceCatgoryCode"
                cacheValue="SERVICE_CATGORY"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="图片" prop="image">
              <Upload v-model="dialogConfig.formData.image" ref="uploadComp" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="currentTab.code != '1'">
            <el-form-item label="视频" prop="video">
              <Upload
                v-model="dialogConfig.formData.video"
                ref="uploadComp2"
                accept=".mp4"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <Editor v-model="dialogConfig.formData.content" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="buttons" v-if="dialogConfig.action !== 'view'">
        <template>
          <el-button @click="closeDialog(dialogConfig)"> 取消 </el-button>
          <el-button type="primary" @click="handlerSubmit"> 提交 </el-button>
        </template>
      </span>
      <span slot="buttons" v-else>
        <template>
          <el-button @click="closeDialog(dialogConfig)">返回</el-button>
        </template>
      </span>
    </edu-dialog>
  </div>
</template>

<script>
import utils from "@/utils";
import mixins from "@/mixins";

import {
  queryKnowledgeCourseList,
  addKnowledgeCourse,
  updateKnowledgeCourse,
  detailKnowledgeCourse,
  deleteKnowledgeCourse,
  publishKnowledgeCourse,
  recommendKnowledgeCourse,
  unPublishKnowledgeCourse,
  unRecommendKnowledgeCourse,
  pageKnowledgeExpert,
} from "@/api/knowledge";

import { queryProduceCategoryTree } from "@/api/common";
import SearchSelect from "@/components/SearchSelect.vue";

const formData = {
  title: "",
  resume: "",
  expertId: "",
  expertName: "",
  fieldCode: "",
  image: "",
  video: "",
  content: "",
};
export default {
  mixins: [mixins],
  components: { SearchSelect },
  data() {
    return {
      currentTab: {},
      queryParams: {
        condition: {},
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      tableList: [],
      dialogConfig: {
        title: "",
        showDialog: false,
        action: "add",
        formData: {},
        rules: {
          title: [
            {
              required: true,
              validator: this.checkTitle,
              trigger: "blur",
            },
          ],
          expertId: [
            {
              required: true,
              message: "此项必填！",
              trigger: "change",
            },
          ],
          levelCode: [
            {
              required: true,
              validator: this.checkLevelCode,
              trigger: "blur",
            },
          ],
        },
      },
      options: {
        fieldCode: [],
        expertName: [],
      },
      deleteKnowledgeCourse: deleteKnowledgeCourse,
      queryProduceCategoryTree: queryProduceCategoryTree,
      pageKnowledgeExpert: pageKnowledgeExpert,
    };
  },
  created() {
    this.initOptions();
  },
  methods: {
    async initOptions() {},
    // 查询
    async query(currentTab) {
      if (currentTab) {
        this.currentTab = currentTab;
      }
      this.queryParams.condition.type = this.currentTab.code;
      formData.type = this.currentTab.code;
      let { returnObj } = await queryKnowledgeCourseList(this.queryParams);
      this.tableList = returnObj.list;
      this.queryParams.total = returnObj.total;
      this.queryParams.pageSize = returnObj.pageSize;
    },
    // 重置
    reset() {
      for (var key in this.queryParams.condition) {
        this.queryParams.condition[key] = "";
      }
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.query();
    },
    // 分页
    handleCurrentChange(row) {
      this.queryParams.pageSize = row.pageSize;
      this.queryParams.pageNum = row.pageNum;
      this.query();
    },
    closeDialog(dialog) {
      dialog.showDialog = false;
      this.$refs["dialogForm"].resetFields();
    },
    openDialog(dialog) {
      dialog.showDialog = true;
    },
    // 新增
    add() {
      this.dialogConfig.title = "新增";
      this.dialogConfig.action = "add";
      this.dialogConfig.formData = utils.clone(formData);
      this.openDialog(this.dialogConfig);
      this.$nextTick(() => {
        this.$refs.selectProfession.init();
        this.$refs.uploadComp && this.$refs.uploadComp.init();
        this.$refs.uploadComp2 && this.$refs.uploadComp2.init();
        setTimeout(() => {
          this.$refs["dialogForm"].clearValidate();
        }, 0);
      });
    },
    checkTitle(rule, value, callback) {
      if (!value) {
        callback(new Error("此项必填！"));
      } else if (value.length > 50) {
        callback(new Error("超出字数限制50"));
      } else {
        callback();
      }
    },
    checkLevelCode(rule, value, callback) {
      if (!value) {
        callback(new Error("此项必填！"));
      } else {
        callback();
      }
    },
    // 修改
    async edit(row) {
      this.dialogConfig.title = "编辑";
      this.dialogConfig.action = "edit";
      let { returnObj } = await detailKnowledgeCourse(row.id);
      this.dialogConfig.formData = utils.clone(returnObj);
      this.openDialog(this.dialogConfig);
      this.$nextTick(() => {
        this.$refs.uploadComp && this.$refs.uploadComp.init();
        this.$refs.uploadComp2 && this.$refs.uploadComp2.init();
      });
    },
    // 保存提交
    handlerSubmit() {
      let params = {
        ...this.dialogConfig.formData,
        type: this.currentTab.code,
        content: this.formatRichText(this.dialogConfig.formData.content),
      };
      this.$refs["dialogForm"].validate((valid) => {
        if (valid) {
          if (this.dialogConfig.action == "add") {
            addKnowledgeCourse(params).then((res) => {
              this.$message({
                type: "success",
                message: "成功",
              });
              this.closeDialog(this.dialogConfig);
              this.query();
            });
          } else {
            updateKnowledgeCourse(params).then((res) => {
              this.$message({
                type: "success",
                message: "成功",
              });
              this.closeDialog(this.dialogConfig);
              this.query();
            });
          }
        }
      });
    },
    // 查看
    view() {
      this.dialogConfig.title = "查看";
      this.dialogConfig.action = "view";
      this.openDialog(this.dialogConfig);
    },
    // 关闭弹框
    handleDialogClose() {
      this.closeDialog(this.dialogConfig);
    },
    // 发布
    async publish(row) {
      this.$confirm(`确认发布?`).then(() => {
        publishKnowledgeCourse([row.id]).then((res) => {
          this.$message({
            type: "success",
            message: "成功",
          });
          this.query();
        });
      });
    },
    // 取消发布
    async revokePublish(row) {
      unPublishKnowledgeCourse([row.id]).then((res) => {
        this.$message({
          type: "success",
          message: "成功",
        });
        this.query();
      });
    },
    // 批量发布
    async batchPublish() {
      let list = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });
      if (!list || list.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }
      this.$confirm(`确认批量发布?`).then(() => {
        publishKnowledgeCourse(list).then((res) => {
          this.$message({
            type: "success",
            message: "批量发布成功",
          });
          this.query();
        });
      });
    },
    // 批量取消发布
    async revokeBatchPublish() {
      let list = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });
      if (!list || list.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }
      this.$confirm(`确认批量取消发布?`).then(() => {
        unPublishKnowledgeCourse(list).then((res) => {
          this.$message({
            type: "success",
            message: "批量取消发布成功",
          });
          this.query();
        });
      });
    },
    // 推荐
    async recommended(row) {
      this.$confirm(`确认推荐?`).then(() => {
        recommendKnowledgeCourse([row.id]).then((res) => {
          this.$message({
            type: "success",
            message: "成功",
          });
          this.query();
        });
      });
    },
    // 取消推荐
    async revokeRecommended(row) {
      unRecommendKnowledgeCourse([row.id]).then((res) => {
        this.$message({
          type: "success",
          message: "成功",
        });
        this.query();
      });
    },
    // 批量推荐
    async batchRecommended() {
      let list = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });
      if (!list || list.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }
      this.$confirm(`确认批量推荐?`).then(() => {
        recommendKnowledgeCourse(list).then((res) => {
          this.$message({
            type: "success",
            message: "批量推荐成功",
          });
          this.query();
        });
      });
    },
    // 批量取消推荐
    async revokeBatchRecommended() {
      let list = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });
      if (!list || list.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }
      this.$confirm(`确认批量取消推荐?`).then(() => {
        unRecommendKnowledgeCourse(list).then((res) => {
          this.$message({
            type: "success",
            message: "批量取消推荐成功",
          });
          this.query();
        });
      });
    },
    // 删除
    async handlerDelete(row) {
      let idField = "id";
      if (row && row[idField]) {
        this.batchDelete(deleteKnowledgeCourse, idField, [row[idField]]);
      } else {
        this.batchDelete(deleteKnowledgeCourse, idField);
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
